import { Node } from "cc";
import { Subscriber, Subscription } from "rxjs";

export function nullifySubscription(key) {
    if (this[key] != null) {
        this[key].unsubscribe();
        this[key] = null;
    }
}

export function deleteSubscription(key) {
    if (this[key] != null) {
        this[key].unsubscribe();
        delete this[key];
    }
}

/** 
 * Subscription
 */
declare module "./internal/Subscription" {
    interface Subscription {
        addTo(target: Subscription | Node): Subscription;
    }
}

/** subscriptionA.add(subscriptionB) => subscriptionB.addTo(subscriptionA) */
Object.defineProperty(Subscription.prototype, 'addTo', {
    value: function (target) {
        if (target instanceof Subscription) {
            // console.log('target is Subscription');
            target.add(this);
        } else if (target instanceof Node) {
            // console.log('target is Node');
            if (!target?.isValid) this.unsubscribe();
            else target.on(Node.EventType.NODE_DESTROYED, _ => this.unsubscribe());
        }
        return this;
    },
    writable: true,
    configurable: true,
});

declare module "./internal/Subscriber" {
    interface Subscriber<T> {
        nextAndComplete(value?: T): void;
    }
}

Object.defineProperty(Subscriber.prototype, 'nextAndComplete', {
    value: function (value) {
        this.next(value);
        this.complete();
    }
});